package com.itheima.api.array.demo01;

public class ArrayBinarySearchDemo01 {

    public static void main(String[] args) {

        System.out.println("--------------------");
        int[] arr = {1,2,3,4,5,6,7,8,9};
        int binarySearch = binarySearch(arr, 7);
        System.out.println(binarySearch);
        System.out.println("-------------------");
    }

    public static int binarySearch(int[] arr, int key){

        int minIndex = 0;
        int maxIndex = arr.length - 1;//8
        int midIndex = (minIndex + maxIndex) / 2;//4
        while (minIndex < midIndex && midIndex < maxIndex) {
            if (arr[midIndex] == key) {
                return midIndex;
            } else if (arr[midIndex] > key) {
                midIndex = (minIndex + (midIndex - 1)) / 2;
            } else {
                midIndex = ((midIndex + 1) + maxIndex) / 2;
            }
        }
        return -1;
    }
}
